/**
 * @file 角色管理
 * @date 2025/09/01 16:57:25
 * @author lyqjob@yeah.net
 */

import {  useEffect, useState  } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, Select, Col, Row, message } from 'antd';
import { adminApi } from "@/services/admin";
import AuthButton from '@/components/AuthButton';
import dayjs from '@/utils/dayjs.js';
import { useNavigate } from 'react-router-dom';

// 角色类型
const roleTypes = {
    'system': '系统内置',
    'custom': '自定义',
    'special': '特殊角色',
}


// 权限层级
const roleLevels = {
    0: '访客',
    10: '普通用户',
    20: '部门管理员',
    30: '业务管理员',
    40: '系统管理员',
    99: '超级管理员'
};

const roleLevelsColor = {
    'system': 'red',
    'custom': 'orange',
    'special': 'blue',
    0: 'green',
    10: 'blue',
    20: 'orange',
    30: 'red',
    40: 'orange',
    99: 'red'
}

const Rolelist = () => {
    const navigate = useNavigate();
    const [selectionType] = useState('checkbox');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [ismenuModal, setIsMenu] = useState(false);
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true)
    const [form] = Form.useForm();
    const [formValues, setFormValues] = useState();
    const [open, setOpen] = useState(false);
    const [roleid] = useState();
    const [pageSize, setPageSize] = useState(10)
    const [current, setCurrent] = useState(1)
    const [total, setTotal] = useState(0)
    const [selectedRowKeys, setSelectedRowKeys] = useState([])
    const [departmentList, setDepartmentList] = useState([]);


    const columns = [
        { title: '角色编码', dataIndex: 'code', key: '', width: 180, fixed: 'left' },
        // {
        //     title: '系统预制',
        //     dataIndex: 'is_system',
        //     key: '',
        //     render: (text) => text == 0 ? '否' : '是',
        //     width:100,
        // },
        {
            title: '角色名称',
            dataIndex: 'name',
            key: '',
            width: 150,
        },
        {
            title: '组织/部门',
            dataIndex: 'department_name',
            key: '',
            width: 150,
        },

        {
            title: '角色类型',
            dataIndex: 'role_type',
            key: '',
            width: 150,
            render: (text) => {
                return (
                    <Tag color={roleLevelsColor[text]} key={text}>
                        {roleTypes[text]}
                    </Tag>
                )
            }

        },
        {
            title: '权限层级',
            dataIndex: 'permission_level',
            key: '',
            width: 150,
            render: (text) => {
                return (
                    <Tag color={roleLevelsColor[text]} key={text}>
                        {roleLevels[text]}
                    </Tag>
                )
            }

        },
        {
            title: '状态', dataIndex: 'status', key: '',
            width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 0 ? 'green' : 'red'} key={tag}>
                        {tag === 0 ? '正常' : '停用'}
                    </Tag>
                )
            }
        },
        {
            title: '创建时间', dataIndex: 'created_at', key: '',
            width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '创建人', dataIndex: 'create_by_name', key: '',
            width: 150,
        },
        {
            title: '修改时间', dataIndex: 'updated_at', key: '',
            width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title: '修改人', dataIndex: 'update_by_name', key: '',
            width: 150,
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: '',
            ellipsis: true,
            width: 200,
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'options',
            width: 150,
            fixed: 'right',
            render: (item) => (
                <Space >

                    {
                        item.is_protected === 0 && item.is_system === 0 ?
                            <AuthButton permission={['role:delete']}>
                                <a onClick={() => deleteRole(item.id)}>删除</a>
                            </AuthButton>
                            : null}
                    {
                        item.is_protected === 0 && item.is_system === 0 ?
                            <AuthButton permission={['role:update']}>
                                <a onClick={() => navigate('/setting/role/info?type=edit&id=' + item.id)}>编辑</a>
                            </AuthButton>
                            : null}

                    {
                        item.is_protected === 0 ?
                            <AuthButton permission={['role:view']}>
                                <a onClick={() => {
                                    navigate('/setting/role/info?type=view&id=' + item.id)
                                }}>查看</a>
                            </AuthButton>
                            : null
                    }
                </Space>
            )
        },
    ];


    const [targetKeys] = useState([]); // 已绑定数据
    const [, setDatasource] = useState([]);// 来源数据

    useEffect(() => {
        getList(current, pageSize)
        getTreeMenus()
        getDepartmentList()
    }, [current, pageSize])

    // 删除角色
    const deleteRole = async (id) => {
        const [err, res] = await adminApi.deleteRole(id);
        if (err) {
            // message.warning('删除失败')
            return
        }
        if (res.code === 200) {
            message.success('删除成功')
            getList(current, pageSize)
        }
    }

    // 选择角色
    const rowSelection = {
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
        getCheckboxProps: record => ({
            disabled: record.is_system === 1
        }),
    };


    // 获取角色列表
    const getList = async (page, limit) => {

        const [err, res] = await adminApi.getAllrole({ page, limit });
        if (err) {
            message.warning('获取用户列表失败')
        }
        if (res.code === 200 && res?.data?.data) {
            setLoading(false)
            setData(res.data.data)
            setTotal(res.data.total)
            window.process.done();
        }

    }

    // 获取部门列表
    const getDepartmentList = async () => {
        const [err, res] = await adminApi.getAllDepartment({ current: 1, pageSize: 1000 })
        if (err) {
            message.warning('获取部门列表失败')
        }
        if (res.code === 200 && res?.data?.data) {
            const list = res.data.data.filter(item => item.type === 1);
            setDepartmentList(list)
        }
    }



    // 获取全部menus
    const getTreeMenus = async () => {
        const [err, result] = await adminApi.getMenuTree();
        if (err) {
            message.error('获取菜单树失败')
        }
        if (result) {
            setDatasource(result.data)
        }
    }


    // 创建角色/编辑角色
    const onCreate = async values => {
        // 编辑
        if (formValues?.id) {
            values.id = formValues.id
            const [err, res] = await adminApi.updateRole(values);
            if (err) {
                // message.warning('获取角色详情失败')
            }
            if (res.code === 200 && res?.data) {
                setFormValues()
                form.resetFields()
                message.success('编辑成功')
                setOpen(false)
                getList(current, pageSize)
            }
            return
        }

        // 创建角色
        const [err, res] = await adminApi.createRole(values)
        if (err) {
            message.error('创建角色失败')
        }
        if (res) {
            message.success('添加成功')
            form.resetFields()
            setOpen(false)
            getList(current, pageSize)
        }

    };

    // 绑定菜单
    const handleOk = async () => {

        const [err, res] = await adminApi.bindMenus({ roleId: roleid, menuIds: targetKeys });
        if (err) {
            return
        }
        if (res.code === 200) {
            message.success('绑定成功')
            setIsMenu(false)
            // getRoleMenuTree(roleid)
        }
    }


    const permissionList = [
        { id: 0, name: '普通用户' },
        { id: 10, name: '部门管理员' },
        { id: 20, name: '系统管理员' }
    ]

    // 批量删除角色
    const batchDeleteRole = async (values) => {
        if (values.length === 0) {
            message.warning('请选择要删除的角色')
            return
        }

        const [err, res] = await adminApi.batchDeleteRole({ ids: values })
        if (err) {
            // message.warning('删除失败')
        }
        if (res) {
            message.success('删除成功')
            getList(current, pageSize)
        }

    };

    return (
        <div className="container">
            <Space>
                {/* <AuthButton permission={['role:create', 'role:list']}> */}
                <Button onClick={() => { navigate(`/setting/role/info?type=add`) }} type="primary" style={{ marginBottom: 16 }}>
                    创建角色
                </Button>
                {/* </AuthButton> */}
                <AuthButton permission={['role:batch:delete', 'role:list']}>
                    <Button danger onClick={() => { batchDeleteRole(selectedRowKeys) }} type="primary" style={{ marginBottom: 16 }}>
                        批量删除
                    </Button>
                </AuthButton>

            </Space>
            <Table
                loading={loading}
                rowKey={'id'}
                columns={columns}
                rowSelection={{ type: selectionType, ...rowSelection }}
                dataSource={data}
                scroll={{ x: 1500, y: 400 }}
                pagination={{
                    pageSize: pageSize,
                    current: current,
                    showPage: true,
                    total: total,
                    showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`,
                    onChange: (page, pageSize) => {
                        setPageSize(pageSize)
                        setCurrent(page)
                        getList(page, pageSize)
                    }
                }}
                onRow={(record) => {
                    return {
                        onClick: () => { }, // 点击行
                        onDoubleClick: () => {
                            if (record.is_protected === 1) {
                                message.warning('受保护角色不能查看编辑')
                                return
                            }
                            navigate(`/setting/role/info?type=view&id=${record.id}`)
                        },
                        onContextMenu: () => { },
                        onMouseEnter: () => { }, // 鼠标移入行
                        onMouseLeave: () => { },
                    };
                }}
            />
            
            

            <Modal
                open={open}
                title={formValues?.id ? '编辑角色' : '创建角色'}
                okText="确定"
                cancelText="取消"
                width={800}
                okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
                onCancel={() => setOpen(false)}
                destroyOnHidden
                forceRender
                modalRender={dom => (
                    <Form
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        layout="horizontal"
                        form={form}
                        name="form_in_modal"
                        initialValues={{ password: '123456', role_type: 'custom', permission_level: 0 }}
                        clearOnDestroy
                        onFinish={values => onCreate(values)}
                        style={{ maxWidth: 800 }}

                    >
                        {dom}
                    </Form>
                )}
            >
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="code"
                            label="用户编码"
                        // rules={[{ required:  true , message: '请添加用户编号' }]}
                        >
                            <Input disabled placeholder='自动生成' />
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="name"
                            label="角色名称"
                            rules={[{ required: true, message: '请添加角色名称' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            name="permission_level"
                            label="权限层级"
                            rules={[{ required: true, message: '请选择部门' }]}
                        >
                            <Select>
                                {
                                    permissionList.map(item => (
                                        <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={8} >
                        <Form.Item
                            name="dept_id"
                            label="部门"
                            rules={[{ required: true, message: '请选择部门' }]}
                        >
                            <Select>
                                {
                                    departmentList.map(item => (
                                        <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            rules={[{ required: true, message: '请选择角色类型' }]}
                            name="role_type"
                            label="角色类型">
                            <Select>
                                <Select.Option key={'custom'} value={'custom'}>自定义</Select.Option>
                                <Select.Option key={'special'} value={'special'}>特殊角色</Select.Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={8} >
                        <Form.Item
                            // labelCol={{ span: 2 }}
                            name="description"
                            label="描述">
                            <Input type="textarea" />
                        </Form.Item>
                    </Col>

                </Row>

            </Modal>
        </div>
    )
}


export default Rolelist;
